package io;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServer {
	private DatagramSocket server = null;
	private int bufSize = 2048;

	public UdpServer(int port, int bufSize) throws SocketException {
		this.bufSize = bufSize;
		server = new DatagramSocket(port);
	}

	public UdpServer(int port) throws SocketException {
		this(port, 2048);
	}

	public void start() {
		while (true) {
			try {
				byte[] buf = new byte[bufSize];
				DatagramPacket packet = new DatagramPacket(buf, bufSize);
				server.receive(packet);
				String msg = new String(buf, 0, packet.getLength());
				String from = packet.getAddress().getHostAddress();
				int port = packet.getPort();
				System.out.println("FROM[" + from + ":" + port + "] - " + msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws SocketException {
		int port = Integer.valueOf(args[0]);
		int bufSize = 2048;
		try {
			bufSize = Integer.valueOf(args[1]);
		} catch (Exception e) {
			bufSize = 2048;
		}
		UdpServer server = new UdpServer(port, bufSize);
		server.start();
	}
}
